<template>
  <div>
    <el-card style="margin: 10px 15px 10px 15px">
      <el-button
        class="go-back-btn"
        @click="goBack"
        type="text"
        icon="el-icon-arrow-left"
        size="small"
        >返回列表</el-button
      >
      <span class="time-remaining">{{ testState }}</span>
    </el-card>
    <div v-show="sense == 1">
      <div
        v-for="(item, index) in detailList"
        :key="item.itemTitle + item.itemContent"
        @click="enterDetail(item)"
      >
        <TestDetail
          :testData="item"
          :index="index + 1"
          :deleteBtnShow="false"
          style="margin: 15px"
        >
          <template #contentRight="{ row }">
            <div v-if="!userId">
              <span v-if="row.submit == 1" style="color: #e6a23c">已作答</span>
              <span v-else-if="row.submit == 0" style="color: #909399"
                >未作答</span
              >
              <span v-else-if="row.isChecked == 1" style="color: #67c23a"
                >{{ row.getScore }}分</span
              >
              <span
                v-else-if="row.isCommitted == 1 && row.fixed == 0"
                style="color: #67c23a"
                >已提交</span
              >
              <span
                v-else-if="row.isCommitted == 1 && row.fixed == 1"
                style="color: #e6a23c"
                >已修改</span
              >
            </div>
            <div v-else>
              <span
                v-if="row.fixed == 1 || row.isChecked == 1"
                style="color: #67c23a"
                >{{ row.getScore }}分</span
              >
              <span v-else style="color: #67c23a">未评改</span>
            </div>
          </template>
        </TestDetail>
      </div>
      <div
        v-if="!this.isEnd && !this.userId"
        style="position: relative; height: 50px; margin-bottom: 20px"
      >
        <div style="position: absolute; right: 0px">
          <div class="submit-times" v-if="state">
            <span class="sub-title">剩余提交次数:</span>
            <span class="sub-time">{{ state.submitTimes }}</span>
          </div>
          <el-button
            v-if="state && !state.isCommitted"
            type="primary"
            size="small"
            style="margin-top: 10px; margin-right: 15px"
            @click="subTest('是否提交试卷')"
            >提交</el-button
          >
          <el-button
            v-if="state && state.isCommitted"
            type="primary"
            size="small"
            style="margin-top: 10px; margin-right: 15px"
            @click="subTest('是否重新提交?', true)"
            >重新提交</el-button
          >
        </div>
      </div>
      <div
        v-if="userId && isEnd"
        style="position: relative; height: 50px; margin-bottom: 20px"
      >
        <div style="position: absolute; right: 0px">
          <el-button
            type="primary"
            size="small"
            style="margin-top: 10px; margin-right: 15px"
            @click="giveScore"
            >提交评改</el-button
          >
        </div>
      </div>
    </div>
    <AnswerView
      v-show="sense == 2"
      :uploadIsShow="userId ? false : true"
      :fileListIsShow="userId ? true : false"
      :document="selectedItem"
    >
      <template #bottom>
        <el-form ref="form"  :rules="rule" v-if="selectedItem && userId" :model="selectedItem" style="margin: 10px 0 0 0">
          <el-form-item label="得分" label-width="50px" prop="getScore">
            <el-input
              v-model="selectedItem.getScore"
              style="width: 60px"
            ></el-input>
            <span class="score">/{{ selectedItem.score }}分</span>
          </el-form-item>
        </el-form>
      </template>
      <template #btn>
        <el-button
          size="small"
          style="margin-top: 10px"
          @click="returnTestDetailList"
          >返回试卷</el-button
        >
        <el-button
          v-if="!isEnd || userId"
          type="primary"
          size="small"
          style="margin-top: 10px"
          @click="save"
          >保存</el-button
        >
      </template>
    </AnswerView>
  </div>
</template>

<script>
import TestDetail from "@/components/testDetail/index";
import AnswerView from "./answerView/index";
export default {
  props: ["testId", "userId"],
  components: {
    TestDetail,
    AnswerView,
  },
  data() {
    let  validateScore = (rule, value, callback) => {
        if (Number.parseInt(value) > this.selectedItem.score) {
          callback(new Error('不能大于分值'));
        } else {
          callback();
        }
      };
    return {
      rule:{
        getScore:[{ validator: validateScore, trigger: 'change'}]
      },
      detailList: [],
      time: null,
      clock: "",
      timer: null,
      sense: 1,
      selectedItem: null,
      state: null,
      isEnd: false,
    };
  },
  methods: {
    async getDetailList(func = () => {}) {
      const res = await this.$API.test.getTestDetailList({
        id: this.userId || this.$store.state.user.id,
        testId: this.testId,
      });
      if (res.code == 200) {
        const state = res.data.state;
        const data = res.data.list;
        this.time = res.data.time;
        this.state = state;
        if (this.$store.state.user.roles!= '总管理员'&&this.time.startTime > Date.now()) {
          this.$router.replace({
            name: "TestList",
          });
        }
        if (state.isChecked == 1) {
          data.forEach((item) => {
            item.isChecked = state.isChecked;
          });
        }
        if (state.isCommitted == 0) {
          data.forEach((item) => {
            item.submit = 0;
          });
        }
        if (state.isCommitted == 1) {
          data.forEach((item) => {
            item.isCommitted = 1;
            item.fixed = 0;
          });
        }
        this.detailList = data;
        func();
      }
    },
    subTest(title, resubmit = false) {
      this.$confirm(title, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then((res) => {
          const msg = this.detailList.map((item) => {
            if (resubmit) {
              return {
                answer: item.answer,
                answerFile: item.answerFile,
                id: item.id,
              };
            } else {
              return {
                answer: item.answer,
                answerFile: item.answerFile,
                testDetailId: item.testDetailId,
              };
            }
          });
          const data = {
            userId: this.$store.state.user.id,
            testId: this.testId,
            list: msg,
          };
          return resubmit
            ? this.$API.test.resubmitTest(data)
            : this.$API.test.submitTest(data);
        })
        .then((res) => {
          this.$message.success("提交成功");
          this.$router.replace({
            name: "TestList",
          });
        });
    },
    getTimer(func = () => {}) {
      const time = parseInt(this.time.endTime - Date.now()) / 1000;
      if (time > 0) {
        let hour = parseInt(time / 3600);
        let min = parseInt((time % 3600) / 60);
        let sec = parseInt((time % 3600) % 60);
        hour = hour < 10 ? `0${hour}` : hour;
        min = min < 10 ? `0${min}` : min;
        sec = sec < 10 ? `0${sec}` : sec;
        this.clock = `考试时间剩余: ${hour}:${min}:${sec}`;
        this.isEnd = false;
        return true;
      } else {
        func();
        this.isEnd = true;
        return false;
      }
    },
    enterDetail(item) {
      this.sense = 2;
      this.selectedItem = item;
    },
    returnTestDetailList() {
      this.sense = 1;
    },
    save() {
      if (this.selectedItem.answerFile.length || this.selectedItem.answer) {
        if (this.selectedItem.isCommitted) {
          this.selectedItem.fixed = 1;
        } else {
          this.selectedItem.submit = 1;
        }
        this.sense = 1;
      } else {
        this.$message.warning("答案不能为空");
      }
    },
    giveScore() {
      this.$confirm("是否提交评改分数", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then((res) => {
          const msg = this.detailList.map((item) => {
            return {
              getScore: item.getScore,
              id: item.id,
            };
          });
          const data = {
            userId: this.userId,
            testId: this.testId,
            list: msg,
          };
          return this.$API.test.giveScore(data);
        })
        .then((res) => {
          this.$message.success("提交成功");
          this.$router.back(1);
        });
    },
    goBack() {
      if (this.userId) {
        this.$router.back(1);
      } else {
        this.$router.replace({
          name: "TestList",
        });
      }
    },
  },
  computed: {
    testState() {
      if (!this.isEnd) {
        return this.clock;
      } else if (this.isEnd && this.state && this.state.isChecked == false) {
        return "考试已结束";
      } else if (this.isEnd && this.state && this.state.isChecked == true) {
        const allScore = this.detailList.reduce((pre,cur)=>{
          pre = pre + parseInt(cur.getScore);
          return pre
        },0)
        return "已评改，"+`总分:${allScore}分`;
      }
    },
  },
  mounted() {
    this.getDetailList(() => {
      if (this.getTimer()) {
        this.timer = setInterval(() => {
          this.getTimer(() => {
            this.subTest("考试已结束,是否提交试卷");
            clearInterval(this.timer);
          });
        }, 1000);
      }
      if (!this.userId && !this.isEnd) {
        const h = this.$createElement;
        this.$notify({
          title: "注意",
          message: h(
            "i",
            { style: "color: teal" },
            "请不要作弊,一旦发现后果自负"
          ),
        });
      }
    });
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
};
</script>

<style scoped>
.test-title {
  color: #409eff;
  font-size: 17px;
  letter-spacing: 3px;
  font-weight: 600;
}
.time-remaining {
  float: right;
  color: #f56c6c;
  letter-spacing: 1px;
  font-size: 15px;
  font-weight: 600;
}
.time-title {
  float: right;
  color: #606266;
  letter-spacing: 1px;
  font-size: 15px;
  display: inline-block;
  margin-right: 10px;
}
.submit-times {
  display: inline-block;
  margin-right: 20px;
}
.sub-title {
  font-size: 15px;
  letter-spacing: 1px;
  color: #606266;
}
.sub-time {
  color: #f56c6c;
  letter-spacing: 1px;
  font-size: 15px;
}
.score {
  display: inline-block;
  font-size: 15px;
  margin-left: 5px;
  letter-spacing: 2px;
  color: #606266;
  font-weight: 600;
}
/deep/ .el-button--text {
  color: #606266;
}
/deep/ .el-button--text:hover {
  color: #409eff;
}
.go-back-btn {
  padding: 0 0 0 0;
}
</style>